# # apps/devices/views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.shortcuts import get_object_or_404
from rest_framework.permissions import AllowAny
from apps.monitoring.utils import log_action

from .models import Device
from .serializers import DeviceSerializer, DeviceControlSerializer

class DeviceListView(APIView):
    permission_classes = [AllowAny]
    def get(self, request):
        # 允许 ?room_id=1 或 ?room_name=客厅 过滤
        room_id = request.query_params.get("room_id")
        room_name = request.query_params.get("room_name")
        qs = Device.objects.all()
        if room_id:
            qs = qs.filter(room__room_id=room_id)
        elif room_name:
            qs = qs.filter(room__name=room_name)
        devices = qs

        serializer = DeviceSerializer(devices, many=True)
        return Response(serializer.data)

    def post(self, request):
        ser = DeviceSerializer(data=request.data)
        if ser.is_valid():
            dev = ser.save()
            log_action(user=request.user if request.user.is_authenticated else None,
                       device=dev, action_type='设备创建',
                       old_value=None,
                       new_value=f"{dev.device_name} ({dev.room.name})")
            return Response({'message':'Device created'}, status=201)
        return Response({'message':ser.errors}, status=400)


class DeviceDetailView(APIView):
    permission_classes = [AllowAny]
    def get(self, request, device_id):
        device = get_object_or_404(Device, device_id=device_id)
        serializer = DeviceSerializer(device)
        return Response(serializer.data, status=status.HTTP_200_OK)

    # PUT —— 修改
    def put(self, request, device_id):
        dev = get_object_or_404(Device, device_id=device_id)
        old = {'name':dev.device_name,'status':dev.status,'val':dev.control_value}
        ser = DeviceSerializer(dev, data=request.data, partial=True)
        if ser.is_valid():
            dev = ser.save()
            log_action(user=request.user if request.user.is_authenticated else None,
                       device=dev, action_type='设备修改',
                       old_value=old, new_value=ser.validated_data)
            return Response({'message':'updated'})
        return Response({'message':ser.errors}, status=400)

    # DELETE —— 删除
    def delete(self, request, device_id):
        dev = get_object_or_404(Device, device_id=device_id)
        log_action(user=request.user if request.user.is_authenticated else None,
                   device=dev, action_type='设备删除',
                   old_value=dev.device_name, new_value=None)
        dev.delete()
        return Response({'message':'deleted'})

class DeviceControlView(APIView):
    permission_classes = [AllowAny]
    def post(self, request, device_id):
        serializer = DeviceControlSerializer(data=request.data)
        if serializer.is_valid():
            value = serializer.validated_data["value"]
            dev = get_object_or_404(Device, device_id=device_id)
            # 直接把遥控值写入数据库
            dev.control_value = value
            dev.save(update_fields=["control_value"])
            return Response({"message": "ok", "device_id": dev.device_id,
                             "control_value": dev.control_value}, status=200)
        return Response({"message": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
